package com.qiku.aspect;

import com.alibaba.fastjson.JSON;
import com.qiku.annotation.SystemLog;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Pointcut("@annotation(com.qiku.annotation.SystemLog)")
    public void pt(){

    }

    @Around("pt()") //环绕通知
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable{
        Object proceed;
        try {
            handleBefore(joinPoint);
            proceed = joinPoint.proceed();
            handleAfter(proceed);
        } finally {
            //结束后换行
            log.info("=====End====="+System.lineSeparator());

        }
        return proceed;
    }

    private void handleAfter(Object proceed) {
        //打印结果
        log.info("Response:"+JSON.toJSONString(proceed));
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取被增强方法上的注解对象
        SystemLog  systemLog = getSystemLog(joinPoint);
        log.info("=====Start=====");
        //打印请求路径URL
        log.info("URL:"+request.getRequestURL());
        //打印描述信息
        log.info("BusinessName:"+systemLog.businessName());
        //打印Http Method
        log.info("Http Method:"+request.getMethod());
        //打印调用Controller的 全路径和执行方法
        log.info("Class Method:"+joinPoint.getSignature().getDeclaringTypeName()+","+((MethodSignature)joinPoint.getSignature()).getName());
        //打印请求的IP
        log.info("IP:"+request.getRemoteHost());
        //打印请求参数
        log.info("Request Args:"+ JSON.toJSONString(joinPoint.getArgs()));
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;
    }
}
